import request from '@/utils/request'

// 获取部门树结构
export function getDepartmentTree() {
    return request({
        url: '/system/dept/tree',
        method: 'get',
        transformResponse: [data => {
            const res = JSON.parse(data)
            if (res.code === 200) {
                // 转换后端返回的数据格式为van-tree-select需要的格式
                const transformDeptData = (depts) => {
                    return depts.map(dept => ({
                        text: dept.text,  // 显示的部门名称
                        id: dept.deptId,      // 部门ID
                        children: dept.children ? transformDeptData(dept.children) : []
                    }))
                }
                return {
                    ...res,
                    data: transformDeptData(res.data)
                }
            }
            return res
        }]
    })
}

// 获取所有员工信息
export function getAllEmployees() {
    return request({
        url: '/employees/all',
        method: 'get',
        transformResponse: [data => {
            const res = JSON.parse(data)
            if (res.code === 200) {
                // 转换后端返回的数据格式，按部门ID分组
                const employeesByDept = {}
                res.data.forEach(employee => {
                    const deptId = employee.deptId
                    if (!employeesByDept[deptId]) {
                        employeesByDept[deptId] = []
                    }
                    employeesByDept[deptId].push({
                        id: employee.employeeId,
                        name: employee.employeeName,
                        phone: employee.phoneNumber
                    })
                })
                return {
                    ...res,
                    data: employeesByDept
                }
            }
            return res
        }]
    })
}

// 获取部门下的员工列表（保留兼容性）
export function getDepartmentEmployees(deptId) {
    return request({
        url: `/api/departments/${deptId}/employees`,
        method: 'get',
        transformResponse: [data => {
            const res = JSON.parse(data)
            if (res.code === 200) {
                // 转换后端返回的数据格式为组件需要的格式
                return {
                    ...res,
                    data: res.data.map(employee => ({
                        id: employee.employeeId,
                        name: employee.employeeName,
                        phone: employee.phoneNumber
                    }))
                }
            }
            return res
        }]
    })
}

// 获取员工详细信息
export function getEmployeeDetail(employeeId) {
    return request({
        url: `/api/employees/${employeeId}`,
        method: 'get'
    })
}